package com.zhentao.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

//配置类，相当于spring.xml文件
@Configuration//表示当前是一个配置类
@ComponentScan(basePackages = "com.zhentao")//扫描包
@PropertySource(value="classpath:db.properties")//加载properties文件
@MapperScan(basePackages = "com.zhentao.dao")
public class SpringConfig {
    @Value("${jdbc_driver}")
    private String driver;
    @Value("${jdbc_url}")
    private String url;
    @Value("${jdbc_username}")
    private String username;
    @Value("${jdbc_password}")
    private String password;
//    数据源
    @Bean  //把对象放入容器，相当于bean标签
    public DataSource getDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setDriverClassName(driver);
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(username);
            druidDataSource.setPassword(password);
        return druidDataSource;
    }
    //工厂
    @Bean
    public SqlSessionFactoryBean getSqlsessionFactory() throws IOException {
        //分页
        Properties properties = new Properties();
        properties.setProperty("helperDialect","mysql");//方言
        properties.setProperty("reasonable","true");//分页合理化

        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setTypeAliasesPackage("com.zhentao.pojo");//别名
        factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mappers/*.xml"));//映射文件加载
        factory.setDataSource(getDataSource());//数据源
       factory.setConfiguration(getConfiguration());
        //分页插件注册
        PageInterceptor pageInterceptor=new PageInterceptor();
        pageInterceptor.setProperties(properties);
        factory.setPlugins(pageInterceptor);
        return factory;
    }
    //驼峰命名
    @Bean
    public org.apache.ibatis.session.Configuration getConfiguration(){
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        return configuration;
    }
}
